package com.crm.service.impl;

import com.crm.entity.Askers;
import com.crm.entity.Netaskers;
import com.crm.entity.Student;
import com.crm.entity.User;
import com.crm.repository.AskersRepository;
import com.crm.repository.NetaskersRepository;
import com.crm.repository.StudentRepositoy;
import com.crm.repository.UserRepository;
import com.crm.service.StudentService;
import com.crm.util.FenyeUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import javax.transaction.Transactional;

import java.util.List;
import java.util.UUID;


@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepositoy studentRepositoy;
    @Autowired
    private AskersRepository askerRepository;
    @Autowired
    private NetaskersRepository netaskersRepository;
    @Autowired
    private UserRepository userRepository;
    @Override
    public FenyeUtil<Student> getAllStudent(Student student,  Integer page,String userid) {
        FenyeUtil<Student> f=new FenyeUtil<>();
        Askers a = new Askers();
        Netaskers n = new Netaskers();
//        User use = userRepository.findById(userid).get();
//        //判断是否是管理员
//        int pd=0;
//        for(int i=0;i<use.getRlist().size();i++) {
//        	if(use.getRlist().get(i).getRoleExplain().equals("管理员")) {
//        		pd=10;
//        	}
//        }
        Integer id = askerRepository.getaskerid(userid);
        Integer netid = netaskersRepository.getnetid(userid);
             n.setNetAskerId(netid);
        	 a.setAskerId(id);
             student.setAskers(a);
             student.setNetakers(n);
             PageRequest of = PageRequest.of(page -1, 10);
             Page<Student> all = studentRepositoy.findAll(get(student), of);
             List<Student> content = all.getContent();
             f.setData(content);
             f.setCount((int) all.getTotalElements());
             f.setCode(0);
             f.setMsg("");
             return f;
      
       
    }

    @Override
    public String  addStudent(Student student,String userId) {
        try {
        	Integer netId=netaskersRepository.getnetid(userId);
        	
        	Netaskers net=netaskersRepository.findById(netId).get();//获得该用户的网络咨询师数据
        //	net.setNetAskerId(netId);
            String uuid = UUID.randomUUID().toString();
            student.setStuid(uuid);
            student.setNetakers(net);
            studentRepositoy.save(student);
            return "添加成功";
        } catch (Exception e) {
            return "添加失败";
        }

    }

    @Override
    public String updateStudent(Student student) {
        try {
        	//findById会查出来optional类型的 这里用get获取到student类型的 不用做转换了
            Student stu=studentRepositoy.findById(student.getStuid()).get();//获得原先值
            stu.setAge(student.getAge());
            stu.setPhone(student.getPhone());
            stu.setStuName(student.getStuName());
            stu.setSex(student.getSex());
            stu.setQQ(student.getQQ());
            
            System.out.println("stuUPdate");
            studentRepositoy.saveAndFlush(stu);
        	 
            return "修改成功";
        } catch (Exception e) {
            return "修改失败";
        }
    }

    @Override
    public String deleteStudent(String stuid) {
    	  try {
              String ids[]= stuid.split(",");
              for(int i=0;i<ids.length;i++){
                  String id=ids[i];
                 studentRepositoy.deleteById(id);
              }
              return "删除成功";
          } catch (Exception e) {
              return "删除失败";
          }
    }

    private Specification<Student> get(Student student) {
        return new Specification<Student>() {
            @Override
            public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.conjunction();
                List<Expression<Boolean>> expressions = predicate.getExpressions();
              //学生姓名
                if(!StringUtils.isEmpty(student.getStuName())){
                    expressions.add(criteriaBuilder.like(root.get("stuName"),"%"+student.getStuName()+"%"));
                }
                //学生手机
                if(!StringUtils.isEmpty(student.getPhone())){
                    expressions.add(criteriaBuilder.like(root.get("phone"),"%"+student.getPhone()+"%"));
                }
                //学生QQ
                if(!StringUtils.isEmpty(student.getQQ())){
                    expressions.add(criteriaBuilder.like(root.get("QQ"),"%"+student.getQQ()+"%"));
                }
                //学生创建时间
                if(!StringUtils.isEmpty(student.getCreateTime())){
                    expressions.add(criteriaBuilder.like(root.get("createTime"),"%"+student.getCreateTime()+"%"));
                }
                //上门时间
                if(!StringUtils.isEmpty(student.getHomeTime())){
                    expressions.add(criteriaBuilder.like(root.get("homeTime"),"%"+student.getHomeTime()+"%"));
                }
                //学生是否付款
                if(!StringUtils.isEmpty(student.getIsPay())){
                    expressions.add(criteriaBuilder.equal(root.get("isPay"),student.getIsPay()));
                }
                //学生是否有效
                if(!StringUtils.isEmpty(student.getIsValid())){
                    expressions.add(criteriaBuilder.equal(root.get("isValid"),student.getIsValid()));
                }
                //学生是否回访
                if(!StringUtils.isEmpty(student.getIsReturnVist())){
                    expressions.add(criteriaBuilder.equal(root.get("isReturnVist"),student.getIsReturnVist()));
                }
                //根据咨询师id查询该咨询师下的学生
                if(student.getAskers().getAskerId()!=null) {
                	expressions.add(criteriaBuilder.equal(root.get("askers").get("askerId"),student.getAskers().getAskerId() ));
                }
                //根据网络咨询师下面的所有学生
                if(student.getNetakers().getNetAskerId()!=null) {
                	expressions.add(criteriaBuilder.equal(root.get("netakers").get("netAskerId"),student.getNetakers().getNetAskerId() ));
                }
                return predicate;
            }
        };
    }

	@Override
	public List<Student> Cha(Integer netAskerId) {
		// TODO Auto-generated method stub
		return studentRepositoy.Cha(netAskerId);
	}
    @Transactional
	@Override
	public Integer FenPeiStu(String Stuid, Integer askerId) {
    	 try {
             String ids[]= Stuid.split(",");
             for(int i=0;i<ids.length;i++){
            	 //这里的id是处理过的 所以传入方法中
                 String id=ids[i];
                 studentRepositoy.FenPeiStu(id, askerId);
             }
             return 1;
         } catch (Exception e) {
             return 0;
         }
  
	}


}
